<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Client;
use fast\Random;

/**
 * Token
 */
class Token extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * @ApiTitle    (检测Token是否过期)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/token/check)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564553074",
    "data": {
    "token": "87d4f4a8-9646-4165-841a-d7235a252daf",
    "expires_in": 2581644
    }
    })
     */
    public function check()
    {
        $token = $this->auth->getToken();
        $tokenInfo = \app\common\library\Token::get($token);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);

//        $token = $this->auth->getToken();
//        $tokenInfo = $this->post('/api/token/check', compact('token'));
//        $this->success('', compact('tokenInfo'));
    }

    /**
     * @ApiTitle    (刷新Token)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/token/refresh)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564553087",
    "data": {
    "token": "c809f686-ccf6-4afd-a191-ff7f49a02775",
    "expires_in": 2592000
    }
    })
     */
    public function refresh()
    {
        //删除源Token
        $token = $this->auth->getToken();
        \app\common\library\Token::delete($token);
        //创建新Token
        $token = Random::uuid();
        \app\common\library\Token::set($token, $this->auth->id, 2592000);
        $tokenInfo = \app\common\library\Token::get($token);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);

//        //删除源Token
//        $token = $this->auth->getToken();
//        $tokenInfo = Client::instance()->post('/api/token/refresh', compact('token'));
//        $this->success('', compact('tokenInfo'));
    }
}
